/*
 * @Author: Await
 * @Date: 2025-04-17 17:30:02
 * @LastEditors: Await
 * @LastEditTime: 2025-04-21 14:26:09
 * @Description: 图表预览面板
 */

import React, { useState, useRef } from 'react';
import {
    Card,
    Space,
    Button,
    Tooltip,
    Spin,
    Dropdown,
    Typography,
    Divider
} from 'antd';
import {
    DownloadOutlined,
    ReloadOutlined,
    SettingOutlined,
    FullscreenOutlined,
    CloseOutlined
} from '@ant-design/icons';
import { useEditor } from './index';
// 直接从charts目录导入，利用index.ts的重新导出
import { ChartBase } from '../Charts';
import { ExportType, PreviewOptions } from '../../types/index';

interface PreviewPanelProps {
    onClose?: () => void;
    fullScreen?: boolean;
}

/**
 * 预览面板组件
 */
const PreviewPanel: React.FC<PreviewPanelProps> = ({ onClose, fullScreen = false }) => {
    const { state } = useEditor();
    const { currentChart, dataSource, dataConfig, loading } = state;

    const chartRef = useRef<any>(null);
    const [previewOptions, setPreviewOptions] = useState<PreviewOptions>({
        theme: 'default',
        renderer: 'canvas',
        animation: true,
        darkMode: false
    });

    // 处理图表导出
    const handleExport = (type: ExportType) => {
        if (chartRef.current) {
            const chart = chartRef.current.getEChartsInstance();
            if (chart) {
                const url = chart.getDataURL({
                    type,
                    pixelRatio: 2,
                    backgroundColor: previewOptions.darkMode ? '#333' : '#fff'
                });

                // 创建下载链接
                const link = document.createElement('a');
                link.download = `${currentChart.title?.text || 'chart'}.${type}`;
                link.href = url;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }
    };

    // 更新预览选项
    const updatePreviewOption = (key: keyof PreviewOptions, value: any) => {
        setPreviewOptions(prev => ({
            ...prev,
            [key]: value
        }));
    };

    // 处理刷新图表
    const handleRefresh = () => {
        if (chartRef.current) {
            const chart = chartRef.current.getEChartsInstance();
            if (chart) {
                chart.clear();
                chart.setOption(currentChart);
            }
        }
    };

    // 根据预览选项获取主题
    const getTheme = () => {
        if (previewOptions.darkMode) return 'dark';
        return previewOptions.theme;
    };

    // 导出下拉菜单项
    const exportMenuItems = [
        {
            key: 'png',
            label: 'PNG格式',
            onClick: () => handleExport('png')
        },
        {
            key: 'jpeg',
            label: 'JPEG格式',
            onClick: () => handleExport('jpeg')
        },
        {
            key: 'svg',
            label: 'SVG格式',
            onClick: () => handleExport('svg')
        }
    ];

    // 设置下拉菜单项
    const settingsMenuItems = [
        {
            key: 'theme-default',
            label: `默认主题 ${previewOptions.theme === 'default' ? '✓' : ''}`,
            onClick: () => updatePreviewOption('theme', 'default')
        },
        {
            key: 'theme-light',
            label: `浅色主题 ${previewOptions.theme === 'light' ? '✓' : ''}`,
            onClick: () => updatePreviewOption('theme', 'light')
        },
        {
            key: 'theme-dark',
            label: `深色主题 ${previewOptions.theme === 'dark' ? '✓' : ''}`,
            onClick: () => updatePreviewOption('theme', 'dark')
        },
        {
            type: 'divider',
            key: 'divider-1'
        },
        {
            key: 'renderer-canvas',
            label: `Canvas渲染器 ${previewOptions.renderer === 'canvas' ? '✓' : ''}`,
            onClick: () => updatePreviewOption('renderer', 'canvas')
        },
        {
            key: 'renderer-svg',
            label: `SVG渲染器 ${previewOptions.renderer === 'svg' ? '✓' : ''}`,
            onClick: () => updatePreviewOption('renderer', 'svg')
        },
        {
            type: 'divider',
            key: 'divider-2'
        },
        {
            key: 'animation',
            label: `动画 ${previewOptions.animation ? '开启 ✓' : '关闭'}`,
            onClick: () => updatePreviewOption('animation', !previewOptions.animation)
        },
        {
            key: 'darkMode',
            label: `深色模式 ${previewOptions.darkMode ? '开启 ✓' : '关闭'}`,
            onClick: () => updatePreviewOption('darkMode', !previewOptions.darkMode)
        }
    ];

    return (
        <div
            style={{
                width: fullScreen ? '100%' : '100%',
                height: fullScreen ? '100vh' : '100%',
                display: 'flex',
                flexDirection: 'column',
                position: 'relative'
            }}
        >
            {/* 工具栏 */}
            <div
                style={{
                    padding: '8px 12px',
                    borderBottom: '1px solid #f0f0f0',
                    display: 'flex',
                    alignItems: 'center'
                }}
            >
                <Typography.Title level={5} style={{ margin: 0, flex: 1 }}>
                    {currentChart.title?.text || '图表预览'}
                </Typography.Title>

                <Space>
                    <Tooltip title="刷新">
                        <Button
                            type="text"
                            icon={<ReloadOutlined />}
                            onClick={handleRefresh}
                            size="small"
                        />
                    </Tooltip>

                    <Dropdown menu={{ items: exportMenuItems }} placement="bottomRight">
                        <Tooltip title="导出">
                            <Button
                                type="text"
                                icon={<DownloadOutlined />}
                                size="small"
                            />
                        </Tooltip>
                    </Dropdown>

                    <Dropdown menu={{ items: settingsMenuItems }} placement="bottomRight">
                        <Tooltip title="设置">
                            <Button
                                type="text"
                                icon={<SettingOutlined />}
                                size="small"
                            />
                        </Tooltip>
                    </Dropdown>

                    {onClose && (
                        <Tooltip title={fullScreen ? "退出全屏" : "全屏"}>
                            <Button
                                type="text"
                                icon={fullScreen ? <CloseOutlined /> : <FullscreenOutlined />}
                                onClick={onClose}
                                size="small"
                            />
                        </Tooltip>
                    )}
                </Space>
            </div>

            {/* 图表容器 */}
            <Card
                variant="borderless"
                style={{
                    flex: 1,
                    position: 'relative',
                    background: previewOptions.darkMode ? '#333' : '#fff',
                    borderRadius: 0,
                    boxShadow: 'none',
                    overflow: 'hidden'
                }}
                styles={{
                    body: { padding: 0, height: '100%' }
                }}
            >
                {loading ? (
                    <div
                        style={{
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center'
                        }}
                    >
                        <Spin size="large" />
                    </div>
                ) : (
                    <ChartBase
                        ref={chartRef}
                        option={currentChart}
                        data={dataSource.data}
                        dataConfig={dataConfig}
                        renderer={previewOptions.renderer}
                        theme={getTheme()}
                        animation={previewOptions.animation}
                        style={{ width: '100%', height: '100%' }}
                    />
                )}
            </Card>
        </div>
    );
};

export default PreviewPanel;